package com.itcast.rpc.client.cluster.impl;

import com.itcast.rpc.client.channel.ProviderService;
import com.itcast.rpc.client.cluster.ClusterStrategy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component
public class PollingClusterStrategy implements ClusterStrategy {
    // 当前对应的节点下标
    private int counter;

    Lock lock = new ReentrantLock();
    /**
     * 轮询
     *
     * @param services
     * @return
     */
    @Override
    public ProviderService select(List<ProviderService> services) {
        try {
            lock.tryLock(10, TimeUnit.SECONDS);
            if (counter >= services.size()){
                counter = 0;
            }
            return services.get(counter++);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;
    }
}
